"use client"

import Link from "next/link"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Toaster } from "@/components/ui/toaster"
import { useToast } from "@/hooks/use-toast"
import { authLogin } from "@/lib/request"
import {post} from '@/lib/api'

export default function Login() {
  const router = useRouter()
  const { toast } = useToast()
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  })
  const [loading, setLoading] = useState(false)
  const [errors, setErrors] = useState({
    username: "",
    password: ""
  })

  const handleChange = (e) => {
    const { id, value, type, checked } = e.target
    setFormData(prev => ({
      ...prev,
      [id]: type === "checkbox" ? checked : value
    }))
    
    // 清除对应字段的错误信息
    if (errors[id]) {
      setErrors(prev => ({
        ...prev,
        [id]: ""
      }))
    }
  }

  const validateForm = () => {
    let valid = true
    const newErrors = { username: "", password: "" }
    
    if (!formData.username.trim()) {
      newErrors.username = "请输入用户名或邮箱"
      valid = false
    }
    
    if (!formData.password) {
      newErrors.password = "请输入密码"
      valid = false
    } else if (formData.password.length < 6) {
      newErrors.password = "密码长度不能少于6位"
      valid = false
    }
    
    setErrors(newErrors)
    return valid
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!validateForm()) return
    
    // setLoading(true)
    const response = await post('/auth/login', formData)
    //登录成功存token，并跳转到首页
    if (response.code === 200) {
      localStorage.setItem('token', response.data.token)
      router.push('/')
    }
    console.log('response', response)
  }
  
  return (
    <div className="flex min-h-screen flex-col bg-gray-100">
      {/* Header */}
      <header className="sticky top-0 z-10 flex h-14 items-center justify-between border-b bg-white px-4 shadow-sm">
        <div className="flex items-center gap-8">
          <Link href="#" className="text-2xl font-bold text-gray-800">
            过早客
          </Link>
          <nav className="hidden md:flex">
            <ul className="flex items-center gap-6">
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  首页
                </Link>
              </li>
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  节点
                </Link>
              </li>
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  成员
                </Link>
              </li>
              <li>
                <Link href="#" className="text-gray-600 hover:text-gray-900">
                  广告招放
                </Link>
              </li>
            </ul>
          </nav>
        </div>
        <div className="flex items-center gap-4">
          <div className="relative w-64">
            <Input
              type="search"
              placeholder="Search"
              className="h-9 w-full rounded-md border border-gray-300 pl-3 pr-10 text-sm"
            />
          </div>
          <div className="flex items-center gap-2">
            <Link href="/login" className="text-sm text-gray-600 hover:text-gray-900">
              登录
            </Link>
            <Link href="/register" className="text-sm text-gray-600 hover:text-gray-900">
              注册
            </Link>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="container mx-auto flex flex-col gap-4 px-4 py-6 md:flex-row">
        {/* Left Content - Login Form */}
        <div className="w-full rounded-md bg-white p-6 md:w-3/4">
          <h1 className="mb-6 text-xl font-medium">用户登录</h1>

          <form className="max-w-md" onSubmit={handleSubmit}>
            <div className="mb-4">
              <div className="flex items-center justify-between">
                <label htmlFor="username" className="mb-1 block w-24 text-right text-sm font-medium">
                  用户名/邮箱
                </label>
                <div className="flex-1 pl-4">
                  <Input 
                    id="username" 
                    className="w-full" 
                    value={formData.username}
                    onChange={handleChange}
                  />
                  {errors.username && <p className="mt-1 text-xs text-red-500">{errors.username}</p>}
                </div>
              </div>
            </div>

            <div className="mb-4">
              <div className="flex items-center justify-between">
                <label htmlFor="password" className="mb-1 block w-24 text-right text-sm font-medium">
                  密码
                </label>
                <div className="flex-1 pl-4">
                  <Input 
                    id="password" 
                    type="password" 
                    className="w-full" 
                    value={formData.password}
                    onChange={handleChange}
                  />
                  {errors.password && <p className="mt-1 text-xs text-red-500">{errors.password}</p>}
                </div>
              </div>
            </div>

            {/* <div className="mb-6">
              <div className="flex items-center justify-between">
                <div className="w-24"></div>
                <div className="flex-1 pl-4">
                  <div className="flex items-center gap-2">
                    <Checkbox 
                      id="remember" 
                      checked={formData.remember}
                      onCheckedChange={(checked) => setFormData(prev => ({ ...prev, remember: !!checked }))}  
                    />
                    <label htmlFor="remember" className="text-sm text-gray-600">
                      记住我
                    </label>
                  </div>
                </div>
              </div>
            </div>   */}

            <div className="flex justify-center md:justify-start md:pl-28">
              <Button 
                type="submit" 
                className="bg-blue-500 hover:bg-blue-600 px-8" 
                disabled={loading}
              >
                {loading ? "登录中..." : "登录"}
              </Button>
            </div>

            <div className="mt-4 md:pl-28">
              <div className="text-sm">
                <Link href="/forgot-password" className="text-blue-500 hover:underline">
                  忘记密码?
                </Link>
                <span className="mx-2 text-gray-400">|</span>
                <Link href="/register" className="text-blue-500 hover:underline">
                  没有账号? 立即注册
                </Link>
              </div>
            </div>
          </form>
        </div>

        {/* Right Sidebar - About */}
        <div className="w-full md:w-1/4">
          <div className="rounded-md bg-white p-4">
            <h3 className="mb-3 font-medium">关于</h3>
            <div className="text-sm text-gray-600 space-y-2">
              <p>
                Guozaoke.com起源于武汉，这里汇聚了一群追求美好，热爱生活的人。他们相信，无论是对论坛兴趣的话题，还是自由的表达观点，一个高效，友好，不断进化的信息交流平台将会成为我们学习，工作，生活的一部分。
              </p>
              <p>从中不仅能获得有价值的资讯，丰富个人阅历，也能帮助更多寻找答案的人解决问题。</p>
            </div>
          </div>
        </div>
      </main>
      <Toaster />
    </div>
  )
}
